package com.itboye.ihomebank.activity.keytwo;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.keytwo.fragment.AdminKeyFragment;
import com.itboye.ihomebank.activity.keytwo.fragment.AdminPassFragment;
import com.itboye.ihomebank.adapter.OrderViewPagerAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.LoadingDialogTwo;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.itboye.ihomebank.util.UIAlertView;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.callback.visible.ResetLockPassCallback;
import com.sitri.sdk.model.ID;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.ihomebank.util.SPUtils.get;

/**
 * 白马锁用户管理界面
 */
public class YongHuAdminActivity extends BaseOtherActivity implements CommonCallback ,Observer{
    View v_statusbar;
    ImageView close_icon;
    TextView add_shap_title_tv,save;

    TextView tv_key;//钥匙
    TextView tv_pass;//密码

    private ViewPager mPager;
    private int currIndex;// 当前页卡编号
    private float offset;// 图片移动的偏移量
    private ImageView image;
    private ArrayList<Fragment> fragmentList;
    private UIAlertView uiAlertView;
    public static boolean addLock = false;

    String uid;
    public String lockid,lockMac,leixing;
    LoadingDialogTwo loadingDialogTwo;
    KeyTwoPresenter keyPresenter;
    @Override
    protected int layout_id() {
        return R.layout.activity_yong_hu_admin;
    }

    @Override
    protected void onInitController() {
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("用户管理");
        uid = get(this, null, SPContants.USER_ID, "") + "";
        keyPresenter=new KeyTwoPresenter(this);
        loadingDialogTwo = new LoadingDialogTwo(this);
        lockid= getIntent().getStringExtra("lockid");
        lockMac= getIntent().getStringExtra("lockMac");
        leixing= getIntent().getStringExtra("type");
        SLock.getServices().setIsDebug(true);
        SLock.getServices().setCommonCallback(this);
        initTextView();
        initImage();
        initViewPager();

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        SLock.getServices().disconnectBle();
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.save:
                uiAlertView = new UIAlertView(YongHuAdminActivity.this, "注意哦", "重置后所有密码失效\n(请保持蓝牙连接)", "是", "取消");
                uiAlertView.show();
                uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                    @Override
                    public void doLeft() {
                        uiAlertView.dismiss();
                        try {
                            loadingDialogTwo.setMessage("正在重置......").show();
                            SLock.getServices().resetLockPass(lockMac,  new ResetLockPassCallback() {
                                @Override
                                public void onProgress(final int progress) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            loadingDialogTwo.setMessage("正在重置......" + progress + "%");
                                            loadingDialogTwo.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                                @Override
                                                public void onDismiss(DialogInterface dialogInterface) {
                                                    SLock.getServices().disconnectBle();
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }catch (Exception e){

                        }
                    }
                    @Override
                    public void doRight() {
                        uiAlertView.dismiss();
                    }
                });
                break;
            default:
                break;
        }
    }
    /*
     * 初始化ViewPager
     */
    public void initViewPager() {
        mPager = (ViewPager) findViewById(R.id.mPager);
        fragmentList = new ArrayList<>();
        Fragment paidanFragment = new AdminKeyFragment();
        Fragment weixiuFragment = new AdminPassFragment();
        fragmentList.add(paidanFragment);
        fragmentList.add(weixiuFragment);

        Intent intent = getIntent();
        int i = intent.getIntExtra("index", 0);
        currIndex = i;
        //
        // //给ViewPager设置适配器
        mPager.setAdapter(new OrderViewPagerAdapter(
                getSupportFragmentManager(), fragmentList));

        mPager.setCurrentItem(i);// 设置当前显示标签页为第一页
        setTextColor(i + 1);

        tranSlate(i, 0);

        mPager.setOnPageChangeListener(new MyOnPageChangeListener());// 页面变化时的监听器

    }

    // 平移动画
    public void tranSlate(int currentItem, long durationMillis) {
        float one = offset;
        Log.v("offest", "" + offset);
        Animation animation = new TranslateAnimation(currIndex * one,
                currentItem * one, 0, 0);// 平移动画
        Log.v("currentoffest", "" + currIndex * one);
        Log.v("currentItem", "" + currentItem * one);
        animation.setFillAfter(true);// 动画终止时停留在最后一帧，不然会回到没有执行前的状态
        animation.setDuration(durationMillis);// 动画持续时间0.2秒
        image.startAnimation(animation);// 是用ImageView来显示动画的
    }



    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        private float one = offset;// 两个相邻页面的偏移量

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageSelected(int arg0) {
            // TODO Auto-generated method stub
            tranSlate(arg0, 200);
            currIndex = arg0;
            int i = currIndex + 1;
            setTextColor(i);
        }
    }

    // 设置顶部条目颜色的变化
    public void setTextColor(int i) {
        switch (i) {
            case 1:
                save.setVisibility(View.GONE);
                tv_key.setTextColor(getResources().getColor(R.color.main_color));
                tv_pass.setTextColor(getResources().getColor(R.color.black));
                break;
            case 2:
                tv_key.setTextColor(getResources().getColor(R.color.black));
                tv_pass.setTextColor(getResources().getColor(R.color.main_color));
                if (leixing.equals("0")){
                    save.setVisibility(View.VISIBLE);
                    save.setText("重置密码");
                }

                break;

            default:
                break;
        }
    }

    // 初始化标签
    public void initTextView() {
        tv_key = (TextView) findViewById(R.id.tv_key);
        tv_pass = (TextView) findViewById(R.id.tv_pass);
        tv_key.setOnClickListener(new txListener(0));
        tv_pass.setOnClickListener(new txListener(1));
    }

    public class txListener implements View.OnClickListener {
        private int index = 0;

        public txListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mPager.setCurrentItem(index);
        }
    }

    /*
     * 初始化图片的位移像素
     */
    public void initImage() {
        image = (ImageView) findViewById(R.id.cursor);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;
        int screenH = dm.heightPixels;
        offset = screenW / 2.0f;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                (int) offset - 20, 2);
        image.setLayoutParams(params);
    }

    String passes;
    @Override
    public void onSuccess(final ResultData resultData) {
        log(resultData.getId(), true, resultData.getData());
        if (resultData.getId() == ID.RESET_LOCK_PASS ) {
            if (loadingDialogTwo != null && loadingDialogTwo.isShowing()) {
                loadingDialogTwo.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showProgressDialog("正在删除，请稍后......",true);
                        String sid= SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                        passes=  resultData.getData();
                        if ("".equals(sid)){
                            keyPresenter.onJianPanPass(uid,lockid,passes, TimesUtils.getStamp());

                        }else {
                            keyPresenter.onJianPanPass(sid,lockid,passes, TimesUtils.getStamp());

                        }
                    }
                });
            }
        }
    }

    @Override
    public void onFailed(ResultError resultError) {
        log(resultError.getId(), false, resultError.getErrorCode().toLog());
        if (loadingDialogTwo != null && loadingDialogTwo.isShowing()) {
            loadingDialogTwo.dismiss();
        }
    }
    private void log(ID id, boolean isSuccess, final String log) {
        if (isSuccess) {
            //  ByAlert.alert(id.name()+":第二个");
        } else {
            ByAlert.alert(TostKey.getStamp(log));
        }
    }
    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        if (entity != null) {
                if (entity.getEventType() == KeyTwoPresenter.jianpanPass_success) {
                    ByAlert.alert("重置成功");
                    finish();
                } else if (entity.getEventType() == KeyTwoPresenter.jianpanPass_fail) {
                    if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                        //切换 锁备用服务器
                        showAlert();
                    }else {
                        ByAlert.alert(entity.getData());
                    }
                }else if (entity.getEventType()== UserPresenter.By_GETSID_success){//获取sid 成功
                    SIDBean data1 = (SIDBean) entity.getData();
                    SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                    SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                    toRefreshData(data1.getSid());
                }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                    ByAlert.alert(entity.getMsg());
                }
        }
    }

    private void toRefreshData(String sid) {
        if ("".equals(sid)){
            keyPresenter.onJianPanPass(uid,lockid,passes, TimesUtils.getStamp());

        }else {
            keyPresenter.onJianPanPass(sid,lockid,passes, TimesUtils.getStamp());

        }

    }
}
